<template>
	<view class="input-group">
		<input :placeholder="placeholder" @input="search" @blur="hideList" v-model="inputValue" />
		<view class="fuzzy-select load-select" v-if="isLoading">
			loading...
		</view>
		<view class="fuzzy-select" v-else-if="isItemsEmpty || list && list.length > 0">
			<template v-if="isItemsEmpty">
				<view class="empty-tips">暂无数据</view>
			</template>
			<template v-else>
				<view class="item" v-for="(item,index) in list" :key="index" @click="select(item)">
					<view >{{ item.name }}</view>
				</view>
			</template>
		</view>
		<!-- <view class="ul">
			<view class="li" v-for="(item,index) in list" :key="index" @click="select(item)">{{item.name}}</view>
		</view> -->
	</view>
</template>

<script>
	export default {
		props: {
			placeholder: String, //默认提示
			fetchSuggestions: Function,
			formData: Object
		},
		data() {
			return {
				inputValue: '',
				list: [],
				// backName: '',
				isLoading: false, // 加载列表
				isItemsEmpty: false // 控制列表为空时提示
			};
		},
		destroyed() {
			clearTimeout(this.t);
		},
		methods: {
			search(e) {
				let val = e.detail.value;
				let arr = [];
				this.isLoading = true
				this.isItemsEmpty = false
				if (val === '') {
					this.isLoading = false
					return
				}
				this.fetchSuggestions(val, this.formData, (items) => {
					if (Array.isArray(items) && items.length > 0) {
						this.isLoading = false
						arr = items;
					} else {
						this.isLoading = false
						this.isItemsEmpty = true
						arr = []
					}
					this.list = arr;
				})

			},
			select(item) {
				// this.backName = item.name;
				this.list = [];
				this.inputValue = item.name
				this.$emit('input',this.inputValue)
				this.$emit('change', item);
			},
			hideList() {
				if(!this.inputValue){
					this.isLoading = false
					this.isItemsEmpty = false
					this.list = [];
				}
				// this.t = setTimeout(() => {
				// 	this.name = this.backName;
				// }, 0);
			}
		}
	}
</script>


<style lang="scss">
	.input-group {
		position: relative;


		input {
			height: 90upx;
			padding-left: 10upx;
			font-size: 30upx;
			box-sizing: border-box;
		}

		// .ul {
		// 	position: absolute;
		// 	left: 0;
		// 	top: 100%;
		// 	width: 100%;
		// 	background: #eaeaea;

		// 	.li {
		// 		border-bottom: 1upx solid gray;
		// 		line-height: 60upx;
		// 	}
		// }
		.load-select {
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 15px 10px;
		}
		
		.fuzzy-select {
			background: #fff;
			width: 500rpx;
			max-height: 50vh;
			overflow-y: scroll;
			position: absolute;
			top: calc(100% + 10px);
			border: 1px solid rgba(0, 0, 0, 0.1);
			box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		
			.empty-tips {
				padding: 15px 10px;
			}
		
			.item {
				line-height: 30px;
				padding: 10px 30px 10px 10px;
				border-bottom: 1px solid rgba(0, 0, 0, 0.1);
			}
		}
	}
</style>
